package org.thanos.demo.redisson.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Arrays;

@Configuration
@SpringBootConfiguration
@EnableConfigurationProperties(RedissonProperties.class)
@ConditionalOnClass(RedissonClient.class)
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RedissonConfig {

    private static final String DELIMITER = ",";

    @Autowired
    private RedissonProperties redissonProperties;

    @Bean(destroyMethod = "shutdown", name = "redissonClient")
    @ConditionalOnMissingBean(RedissonClient.class)
    public RedissonClient redissonClient() throws IOException {
        if (StringUtils.isEmpty(redissonProperties.getNodes())) {
            throw new NullPointerException("nodes must not be null");
        }
        String nodes = redissonProperties.getNodes();
        Config config = new Config();
        String[] nodeArr = nodes.split(DELIMITER);
        if (nodeArr.length == 1) {
            config.useSingleServer().setAddress(nodeArr[0]);
        }
        if (nodeArr.length > 1) {
            Arrays.stream(nodeArr).forEach(node -> config.useClusterServers().addNodeAddress(node));
        }
        return Redisson.create(config);
    }
}
